package com.example.navigation.api

import com.example.navigation.api.device.DeviceApi
import com.example.navigation.api.login.LoginApi
import com.example.navigation.api.navigation.NavigationApi
import com.example.navigation.api.statistic.StatisticApi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * Created with IntelliJ IDEA.
 * @Author: Liao Run
 * @Date: 2024-06-08 10:04
 * @Description:
 **/
@Module
@InstallIn(SingletonComponent::class)
object RequestManager {

    // ========================= 每个模块的Api =========================


    /**
     * @param retrofit 这个retrofit 就是 getRetrofitInstance()，自动扫描赋值
     * @return
     */
    @Singleton
    @Provides
    fun loginApi(retrofit: Retrofit): LoginApi {
        return retrofit.create(LoginApi::class.java)
    }

    @Singleton
    @Provides
    fun navigationApi(retrofit: Retrofit): NavigationApi {
        return retrofit.create(NavigationApi::class.java)
    }

    @Singleton
    @Provides
    fun deviceApi(retrofit: Retrofit): DeviceApi {
        return retrofit.create(DeviceApi::class.java)
    }

    @Singleton
    @Provides
    fun statisticApi(retrofit: Retrofit): StatisticApi {
        return retrofit.create(StatisticApi::class.java)
    }
    // ================================================================


    private val baseUrl = "http://120.79.24.109:8018"

    private val CONNECTION_TIME_OUT = 10L // 连接超时时间

    private val WRITE_TIME_OUT = 10L // 写入超时时间

    private val READ_TIME_OUT = 10L // 读取超时时间

    @Singleton
    @Provides
    fun getOkHttpClient(tokenInterceptor: TokenInterceptor): OkHttpClient {
        // 打印哇网络日志的拦截器
        val interceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)

        return OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .addNetworkInterceptor(tokenInterceptor)
            .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
            .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
            .build()
    }

    /**
     * @param client 这个client 就是 getOkHttpClient()，自动扫描赋值
     * @return
     */
    @Singleton
    @Provides
    fun getRetrofitInstance(client: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(client) // 可以不设置，Retrofit会自动生成一个client
            // 增加返回值为Gson的支持(以实体类返回)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

}